/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.procurement.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.javaeye.procurement.dto.MaterialsRequest;

public class MaterialsRequestDAOHibernate extends HibernateDaoSupport implements MaterialsRequestDAO {
	
	public void saveMaterialsRequest(MaterialsRequest request) {
		getHibernateTemplate().saveOrUpdate(request);
		logger.debug("MaterialsRequest id set to: " + request.getId());
	}
	
	public MaterialsRequest getMaterialsRequest(int requestId) {
		return (MaterialsRequest)getHibernateTemplate().get(MaterialsRequest.class, requestId);
	}
	
	@SuppressWarnings("unchecked")
	public List<MaterialsRequest> getWaitingMaterialsRequests(final MaterialsRequest condition) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria crit = session.createCriteria(MaterialsRequest.class);
				String orderId = condition.getOrderId();
				if (!"".equals(orderId)) {
					crit.add(Restrictions.eq("orderId", orderId));
				}
				String materialsCode = condition.getCode();
				if (!"".equals(materialsCode)) {
					crit.add(Restrictions.eq("code", materialsCode));
				}
				crit.addOrder(Order.asc("finishDate"));
				return crit.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}
	
	@SuppressWarnings("unchecked")
	public long getCountByMaterialsId(int materialsId) {
		final String queryString = "select count(r.id) from MaterialsRequest r where r.materialsId=?";
		List result = getHibernateTemplate().find(queryString, materialsId);
		long count = 0;
		if (result.size() > 0) {
			count = (Long)result.get(0);
		}
		return count;
	}

}
